package cn.ztuo.bitrade.service;


import cn.ztuo.bitrade.dao.IeoOdfDao;
import cn.ztuo.bitrade.dao.MemberWalletDao;
import cn.ztuo.bitrade.entity.Coin;
import cn.ztuo.bitrade.entity.IeoOdf;
import cn.ztuo.bitrade.entity.MemberWallet;
import cn.ztuo.bitrade.entity.QIeoOdf;
import cn.ztuo.bitrade.util.PredicateUtils;
import cn.ztuo.bitrade.vo.IeoEmptionVO;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class IeoOdfService {
    @Autowired
    private IeoOdfDao IeoOdfDao;
    @Autowired
    private MemberWalletDao memberWalletDao;
    @Autowired
    private CoinService coinService;
    @Autowired
    private MemberService memberService;
    /**
     * 获取所公募信息
     * @return
     */
    public List<IeoOdf> findAll(){
        return IeoOdfDao.findAll();
    }

    public IeoOdf save(IeoOdf ieoOdf){
        return IeoOdfDao.save(ieoOdf);
    }



    /**
     * 获取单个公募信息
     * @return
     */
    public IeoOdf findById(Long id){
        return IeoOdfDao.findOne(id);
    }

    public List<IeoOdf> isBuyOre(Long id){
        return IeoOdfDao.findAll();
    }

    public int subAmount(Long id, BigDecimal number){
        return IeoOdfDao.subAmount(id,number);
    }


    public Page<IeoOdf> getByPage(IeoEmptionVO ieoEmptionVO) throws Exception {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();
  /*
        if (StringUtils.isNotEmpty(ieoEmptionVO.getStartTime())) {
            booleanExpressions.add(QIeoOdf.ieoOdf.createTime.goe(DateUtil.stringToDate(ieoEmptionVO
                    .getStartTime())));
        }
        if (StringUtils.isNotEmpty(ieoEmptionVO.getEndTime())) {
            booleanExpressions.add(QIeoOdf.ieoOdf.createTime.loe(DateUtil.stringToDate(ieoEmptionVO
                    .getEndTime())));
        }
        if (ieoEmptionVO.getStatus() != 3) {
            int status = ieoEmptionVO.getStatus();
          Date date = new Date();
            if ("1".equals(status)) {
                booleanExpressions.add(QIeoEmption.ieoEmption.startTime.gt(date));
            } else if ("2".equals(status)) {
                booleanExpressions.add(QIeoEmption.ieoEmption.startTime.lt(date));
                booleanExpressions.add(QIeoEmption.ieoEmption.endTime.goe(date));
            } else if ("3".equals(status)) {
                booleanExpressions.add(QIeoEmption.ieoEmption.endTime.lt(date));
            }
        }
 */
        booleanExpressions.add(QIeoOdf.ieoOdf.status.in(0, 1, 2,3));
        if (ieoEmptionVO.getId() != null) {
            booleanExpressions.add(QIeoOdf.ieoOdf.id.eq(ieoEmptionVO.getId()));
        }
        Predicate predicate = PredicateUtils.getPredicate(booleanExpressions);
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(ieoEmptionVO.getPageNum() - 1, ieoEmptionVO.getPageSize(), sort);
        return IeoOdfDao.findAll(predicate, pageable);
    }

    /**
     * sale ==coin == 发售币种
     * raise_coin ==buyCoin 募集币种
     * @param amount
     * @param ieoEmption
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public int subAmount(BigDecimal amount, IeoOdf ieoEmption, Long userId) throws Exception {
        //获取总价
        BigDecimal receAmount = amount.multiply(ieoEmption.getRatio()).setScale(4, BigDecimal.ROUND_DOWN);
        //减少募集库存
        int subResult = IeoOdfDao.subAmount(ieoEmption.getId(), amount);
        if (subResult > 0) {
            //raise_coin募集USDT
            Coin raiseCoin = coinService.findByUnit(ieoEmption.getBuyCoin());
            //扣减用户募集币种总额
            MemberWallet raiseWallet = memberWalletDao.findByCoinAndMemberId(raiseCoin, userId);
            int subWallet = memberWalletDao.decreaseBalance(raiseWallet.getId(), receAmount);
            if (subWallet == 1) {
                //增加用户认购币种
                Coin saleCoin = coinService.findByUnit(ieoEmption.getCoin());
                MemberWallet saleWallet = memberWalletDao.findByCoinAndMemberId(saleCoin,userId);
                if (saleWallet == null){
                    int insertResult = memberService.saveWallet(ieoEmption.getCoin(),userId,amount);
                    if (insertResult == 1){
                        return 1;
                    }else {
                        throw new Exception("增加用户余额异常："+userId+"，coin:"+ieoEmption.getCoin());
                    }
                }else {
                    int addResult = memberWalletDao.increaseBalance(saleWallet.getId(),amount);
                    if (addResult == 1){
                        return 1;
                    }else {
                        throw new Exception("增加用户余额异常："+userId+"，coin:"+ieoEmption.getCoin());
                    }
                }
            } else {
                throw new Exception("扣减用户余额异常：" + userId + "，coin:" + ieoEmption.getBuyCoin());
            }
        } else {
            return 0;
        }
    }

}
